package com.misalen.doc;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.filechooser.FileSystemView;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.misalen.utils.DateUtil;
import org.misalen.web.database.repository.mysql.SysWordbookItemRepository;
import org.misalen.web.database.repository.mysql.SysWordbookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.misalen.doc.model.DocClassify;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/applicationContext.xml", "classpath:spring/spring-servlet.xml" })
public class Main {
	@Autowired
	protected SysWordbookRepository sysWordbookRepository;
	@Autowired
	protected SysWordbookItemRepository sysWordbookItemRepository;

	private static String packageName = "org.misalen.web.server.controllers.user";
	private static String[] templateName = { "/com/misalen/doc", "doc.ftl" };
	private static File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
	private static String docPath = desktopDir.getAbsolutePath() + "\\" + "广告文档" + "\\api\\";

	@Test
	public void start() throws Exception {
		System.err.println(desktopDir.getAbsolutePath());
		FilterFile filterFile = new FilterFile();
		List<DocClassify> classifies = AnnotationUtil.getDocClassifies(packageName, filterFile, sysWordbookRepository,
				sysWordbookItemRepository);
		JSONArray array = JSON.parseArray(JSON.toJSONString(classifies, true));
		String docName = DateUtil.formatDate(DateUtil.getToday()) + ".html";
		YUIDoc(array, docPath + docName);
	}

	private static void YUIDoc(JSONArray array, String docPath) throws Exception {
		System.err.println(docPath);
		Configuration cfg = new Configuration(new Version(2, 3, 0));
		cfg.setClassForTemplateLoading(Main.class, templateName[0]);
		cfg.setSharedVariable("upperFC", new UpperFirstCharacter());
		Template template = cfg.getTemplate(templateName[1]);
		FileOutputStream fos = new FileOutputStream(new File(docPath));
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("date", DateUtil.formatDate(DateUtil.getToday()));
		data.put("classifies", array);
		template.process(data, new OutputStreamWriter(fos, "utf-8"));
	}

}
